package com.jyl.sort.merge;

import java.util.Arrays;

/**
 * 归并排序
 *
 * @ClassName MergeSort
 * @Author admin
 * @Date 2024/6/15
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] arr = {93,80,52,49,31,57,56,27,9,55};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    // 提供对外访问的方法
    public static void sort(int[] nums) {
        sort(nums, 0, nums.length - 1);
    }

    /**
     * 步骤：
     *    1. 拆分
     *    2. 归并
     *
     * 时间复杂度：O(nlogn)
     * 空间复杂度：O(n)
     *
     */
    protected static void sort(int[] nums, int start, int end) {
        if (start >= end) {
            return;
        }

        int mid = (start + end) / 2;

        sort(nums, start, mid);
        sort(nums, mid + 1, end);
        merge(nums,start,mid,end);

    }

    /**
     * 需求：将
     * arr1[start--mid] ,
     * arr2[mid+1--end]
     * 合并到 nums[start--end]
     */
    protected static void merge(int[] nums, int start, int mid, int end) {
        int[] result = new int[end - start + 1];

        int arrOnePointer = start;
        int arrTwoPointer = mid + 1;
        int resultPointer = 0;

        // arrOnePointer 和 arrTwoPointer 的最大取值均能取到 mid 和 end 所以得 <=
        while (arrOnePointer <= mid && arrTwoPointer <= end) {
            result[resultPointer++] = nums[arrOnePointer] < nums[arrTwoPointer] ? nums[arrOnePointer++] : nums[arrTwoPointer++];
        }

        while (arrOnePointer <= mid) {
            result[resultPointer++] = nums[arrOnePointer++];
        }

        while (arrTwoPointer <= end) {
            result[resultPointer++] = nums[arrTwoPointer++];
        }

        //将临时数组的内容拷贝到原数组指定区间
        System.arraycopy(result, 0, nums, start, result.length);
    }

}
